package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Category;
import com.itheima.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Slf4j
@RequestMapping("/category")
@RestController
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 添加菜品
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info(category.toString());
        boolean flag=categoryService.save(category);
        if(flag){
            return R.success("新增菜品信息成功");
        }
      return R.error("新增菜品信息失败");
    }

   @GetMapping("/page")
    public R pageQuery(int page,int pageSize){
       Page<Category> pageInfor=new Page<>(page,pageSize);
       LambdaQueryWrapper<Category> lqw=new LambdaQueryWrapper<>();
       lqw.orderByAsc(Category::getSort);
       categoryService.page(pageInfor,lqw);
       return R.success(pageInfor);
   }

   @PutMapping
    public R<String> update(@RequestBody Category category){

       boolean flag=categoryService.updateById(category);
       if(flag){
           return R.success("修改菜品信息成功");
       }
       return R.error("修改菜品信息失败");
   }

    /**
     * 删除
     * @param id
     * @return
     */
   @DeleteMapping
    public R<String> deleteById(@RequestParam("id") Long id){
       log.info("id:{}",id);
       boolean flag=categoryService.removeById(id);
       System.out.println(flag);
       if(flag){
           return R.success("删除菜品信息成功");
       }
       return R.error("删除菜品信息失败");
   }

    /**
     * 获取菜品分类列表
     * @return
     */
   @GetMapping("/list")
    public R getCategoryList(Integer type){
       List<Category> list;
       if(type==null){
           list=categoryService.list();
       }else{
           LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
           lqw.eq(Category::getType,type);
           list = categoryService.list(lqw);
       }
       return R.success(list);
   }


}
